package com.bonc.modules.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.bonc.common.utils.*;
import com.bonc.datasource.annotation.DataSource;
import com.bonc.modules.business.entity.*;
import com.bonc.modules.business.service.TbWorkOrderInfoService;
import com.bonc.modules.business.service.TbWorkOrderReplyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bonc.modules.business.dao.TbWorkOrderReproceeDao;
import com.bonc.modules.business.service.TbWorkOrderReproceeService;

import javax.annotation.Resource;

@DataSource("data")
@Service("tbWorkOrderReproceeService")
public class TbWorkOrderReproceeServiceImpl extends ServiceImpl<TbWorkOrderReproceeDao, TbWorkOrderReproceeEntity> implements TbWorkOrderReproceeService {

    @Autowired
    private TbWorkOrderReproceeService tbWorkOrderReproceeService;

    @Autowired
    private TbWorkOrderInfoService tbWorkOrderInfoService;

    @Autowired
    private TbWorkOrderReplyService tbWorkOrderReplyService;

    @Resource
    private TbWorkOrderReproceeDao tbWorkOrderReproceeDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String identifier = (String)params.get("identifier");
        IPage<TbWorkOrderReproceeEntity> page = this.page(
                new Query<TbWorkOrderReproceeEntity>().getPage(params),
                new QueryWrapper<TbWorkOrderReproceeEntity>().like(StringUtils.isNotBlank(identifier),"identifier", identifier)
        );

        return new PageUtils(page);
    }

    @Override
    public boolean save(TbWorkOrderReproceeEntity tbWorkOrderReprocee) {
        return SqlHelper.retBool(this.getBaseMapper().insert(tbWorkOrderReprocee));
    }

    @Override
    public List<Map<String, Object>> queryReproceeList() {
        return this.baseMapper.queryReproceeList();
    }

    @Override
    public AtomicReference<String> postOrderReproceeService(TbWorkOrderReproceeEntity orderReprocee) {
        /*LambdaQueryWrapper<TbWorkOrderReproceeEntity> queryWrapper = new LambdaQueryWrapper<>();
        List<TbWorkOrderReproceeEntity> list = tbWorkOrderReproceeService.list(queryWrapper);*/
        AtomicReference<String> res = new AtomicReference<>("");
        AtomicReference<String> req = new AtomicReference<>("");

        /*list.forEach(orderReprocee->{

        });*/

        String url = "http://10.254.30.252:3900/api/v2/sync/CSVC/ReprocessCSS";
        SupermanUtil util = new SupermanUtil();

        JSONObject content = new JSONObject();
        content.put("Identifier", orderReprocee.getIdentifier());
        content.put("Creator", orderReprocee.getReviewer());
        content.put("CreatorTel", orderReprocee.getReviewerTel());
        content.put("ReprocessingOpinion", orderReprocee.getReprocessingOpinion());

        Map<String, Object> param = ResolveParamUtils.getAllParam(content);

        req.set(JSON.toJSONString(param));
        res.set(util.sendPost(url, req.get()));

        TbWorkOrderInfoEntity tbWorkOrderInfo = new TbWorkOrderInfoEntity();
        tbWorkOrderInfo.setIdentifier(orderReprocee.getIdentifier());
        tbWorkOrderInfo.setState("07");//工单状态更改为再处理
        tbWorkOrderInfoService.updateById(tbWorkOrderInfo);

        int num = tbWorkOrderReproceeDao.selectMaxIdFromReprocee();
        num = num+1;
        orderReprocee.setId(num);

        tbWorkOrderReproceeService.save(orderReprocee);

        return res;
    }

    @Override
    public ReplyCommon ReprocessCSS(TbCommonParamInfoEntity tbCommonParamValue) {
        String content = "";
        String rspCode = "";
        String rspDesc = "";

        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dateFormat1= new SimpleDateFormat("yyyyMMddHHmmss");
        String cutOffDay = dateFormat.format(calendar.getTime());
        String handingTime = dateFormat1.format(calendar.getTime());
        String transIDO = handingTime + System.currentTimeMillis();
        String providePartyID = "CSVB3510";

        /*String signjy = ResolveParamUtils.analysisAllParam(tbCommonParamValue);
        String sign = tbCommonParamValue.getSign();
        if(sign == signjy || sign.equals(signjy)){

        }else{
            rspCode = "20207";
            rspDesc = "非法的签名";
        }*/
        content = tbCommonParamValue.getContent();
        TbWorkOrderReproceeEntity tbWorkOrderReprocee = JSONObject.parseObject(content,TbWorkOrderReproceeEntity.class);
        JSONObject jobj = JSONObject.parseObject(content);
        if(StringUtils.isBlank(tbWorkOrderReprocee.getIdentifier())){
            rspCode = "20101";
            rspDesc = "缺少必须的参数";
        }else{
            //通过工单编号 判断该工单是否存在  不存在返回报错信息  存在进行下一步操作
            TbWorkOrderInfoEntity tbWorkOrderInfo = tbWorkOrderInfoService.getById(tbWorkOrderReprocee.getIdentifier());
            TbWorkOrderReplyEntity tbWorkOrderReply = new TbWorkOrderReplyEntity();

            if(tbWorkOrderInfo == null){
                rspCode = "20000";
                rspDesc = "此工单不存在，请检查！";
            }else{
                if(tbWorkOrderInfo.getState().equals("04")){
                    tbWorkOrderReprocee.setReviewer(jobj.get("Creator").toString());
                    tbWorkOrderReprocee.setReviewerTel(jobj.get("CreatorTel").toString());
                    boolean num = tbWorkOrderReproceeService.save(tbWorkOrderReprocee);
                    tbWorkOrderReply.setStatus("0");
                    tbWorkOrderReply.setIdentifier(tbWorkOrderReprocee.getIdentifier());
                    tbWorkOrderReplyService.updateById(tbWorkOrderReply);
                    tbWorkOrderInfo.setState("07");//工单状态更改为再处理
                    tbWorkOrderInfoService.updateById(tbWorkOrderInfo);
                    if(num == true){
                        rspCode = "00000";
                        rspDesc = "success";
                    }else{
                        rspCode = "20000";
                        rspDesc = "基础服务系统内部错误";
                    }
                }else{
                    rspCode = "20000";
                    rspDesc = "当前工单未完成，不得进行再处理";
                }
            }
        }
        return ReplyCommon.ok(transIDO,cutOffDay,providePartyID,rspCode,rspDesc);
    }

}
